# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict
from datetime import datetime

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '810321': {  # 百捷支付  alipay-wap  100-5000  2.6%  witch
        'API_KEY': '0c8db37e1997c5e3f480b7ed3941ce1a',
        'gateway': 'http://api.bjpays.com/wap/pay',
        'query_gateway': 'http://api.bjpays.com/ebank/queryorder',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        s += '%s=%s&' % (k, parameter[k])
    s += 'KEY=%s' % key
    _LOGGER.info("baijiepay sign str: %s", s)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    _LOGGER.info("baijiepay verify_notify params is: %s", params)
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign.lower() != calculated_sign.lower():
        _LOGGER.info("baijiepay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def verify_query_response_sign(params, key):
    _LOGGER.info("baijiepay query_response_sign params is: %s", params)
    sign = params['data']['sign']
    params['data'].pop('sign')
    calculated_sign = generate_sign(params['data'], key)
    if sign.lower() != calculated_sign.lower():
        _LOGGER.info("baijiepay query_response_sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'alipay':
        return '17'
    return '17'


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('merchantCode', app_id),
        ('outOrderId', str(pay.id)),
        ('totalAmount', int(pay_amount * 100)),
        ('goodsName', 'charge'),
        ('goodsExplain', ''),
        ('orderCreateTime', datetime.now().strftime('%Y%m%d%H%M%S')),
        ('merUrl', '{}/pay/api/{}/baijiepay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('noticeUrl', '{}/pay/api/{}/baijiepay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('payType', _get_pay_type(service)),
        ('arrivalType', '1100'),
        ('ext', ''),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("baijiepay create: %s", json.dumps(parameter_dict))
    html_text = _build_form(parameter_dict, _get_gateway(app_id))
    cache_id = redis_cache.save_html(pay.id, html_text)
    _LOGGER.info('baijiepay url: %s', settings.PAY_CACHE_URL + cache_id)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# SUCCESS
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("baijiepay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['outOrderId']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('baijiepay event does not contain pay ID')
    pay = order_db.get_pay(str(pay_id))
    if not pay:
        raise ParamError('baijiepay pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('baijiepay pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    total_fee = float(data['totalAmount']) / 100
    trade_no = data['outOrderId']
    extend = {
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    _LOGGER.info('baijiepay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
    order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
    # async notify
    async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('merchantCode', app_id),
        ('outOrderId', pay_id),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info('baijiepay query data, %s', parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info('baijiepay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        _LOGGER.info("baijiepay query response body: %s", data)
        verify_query_response_sign(data, api_key)
        mch_id = pay_order.mch_id
        trade_status = str(data['data']['replyCode'])
        total_fee = float(data['data']['amount']) / 100
        trade_no = data['data']['outOrderId']
        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }
        if trade_status == '00':
            check_channel_order(pay_id, total_fee, app_id)

            _LOGGER.info('baijiepay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
